import {
  regist,
  login,
  getCustomer
} from '../../api/customerApi.js'

import {
  getToken,
  setToken
} from '../../utils/local.js'

import router from '../../router/index.js'


export default {
  namespaced: true,
  state: {
    user_phone: '',
    user_password: '',
    confirm_password: '',
    user_name: '',
    login_customer: null
  },
  getters: {},
  mutations: {
    //保存用户昵称
    set_login_customer(state, value) {
      state.login_customer = value
    }
  },
  actions: {
    //注册
    customer_regist(context) {
      regist({
        user_phone: context.state.user_phone,
        user_password: context.state.user_password,
        user_name: context.state.user_name,
      }).then(response => {
        //注册成功
        if (response.data.httpcode == 200) {
          // 自动登录
          context.dispatch('customer_login')
        } else {
          alert(response.data.message)
        }
      })
    },
    //登录
    customer_login(context) {
      login({
        username: context.state.user_phone,
        password: context.state.user_password,
      }).then(response => {
        //登录成功
        if (response.data.httpcode == 200) {
          //保存token到localStorage
          setToken(response.data.data)
          //保存用户信息
          context.dispatch('load_customer')
          //跳转到首页
          router.push({
            path: '/'
          })
        }
      })
    },
    //获取用户信息
    load_customer(context) {
      getCustomer({}).then(response => {
        if (response.data.httpcode == 200) {
          context.commit('set_login_customer', response.data.data)
        }
      })
    }

  },
  modules: {}
}
